<template>
  <div class="tree_title">
    <div class="title">模型分类</div>
    <Button type="primary" @click="handleCreateType()">创建分类</Button>
  </div>

  <Input v-model="searchValue" placeholder="请输入关键字" clearable @on-change="searchChange" />

  <el-tree ref="treeRef" :data="departmentTree" default-expand-all :props="{
      children: 'children',
      label: 'name'
    }" :expand-on-click-node="false" highlight-current 
    :current-node-key="0" node-key="id"
    :filter-node-method="filterNode" @node-click="treeSelected" />

  <TypeEditDialog ref="typeEditDialogRef" v-if="typeEditDialogDisplay" :treeData="departmentTree" @submit="typeEditSuccess" @cancel="typeEditDialogDisplay = false" />
</template>

<script setup>
import { ref, onMounted, nextTick, getCurrentInstance } from 'vue'

import { modelManage } from '@/api/modules/modelSetting'
import { listToTree } from '@/util/index'
import { Message } from 'view-ui-plus'
import { ElTree } from 'element-plus'
import TypeEditDialog from './TypeEditDialog.vue'
// import 'element-plus/theme-chalk/el-tree.css'

const emit = defineEmits(['selected'])
const { proxy } = getCurrentInstance()
const departmentTree = ref([
  {
    name: '模型分类',
    id: 0,
    children: []
  }
])

const searchValue = ref('')
const treeRef = ref(null)

const typeEditDialogDisplay = ref(false)
const typeEditDialogRef = ref(null)

const getTreeData = (reset) => {
  return modelManage.typeList().then(({ data }) => {
    departmentTree.value[0].children = listToTree(data, {
      id: 'id',
      children: 'children',
      pid: 'parentid'
    })

    if(!reset) return

    treeSelected(departmentTree.value[0])
  })
}

const searchChange = () => {
  treeRef.value.filter(searchValue.value)
}

const treeSelected = node => {
  emit('selected', node)
}

const filterNode = (value, data) => {
  if (!value) return true

  return data.name.includes(value)
}

const handleCreateType = (id) => {
  typeEditDialogDisplay.value = true

  nextTick(()=>{
    typeEditDialogRef.value.initDialog(id)
  })
}

const handleDeleteType = (id) => {
  proxy.$Modal.confirm({
    mask: false,
    title: '警告',
    content: '<p>是否删除该数据?</p>',
    okText: '确认',
    cancelText: '取消',
    onOk: async () => {
      await modelManage.typeDelete({
        data: {
          id
        }
      })
      Message.success('删除成功')
      getTreeData()

      treeRef.value.setCurrentKey(0)
      treeSelected(departmentTree.value[0])
    }
  })
}

const typeEditSuccess = () => {
  typeEditDialogDisplay.value = false
  getTreeData()
}

onMounted(() => {
  getTreeData(true)
})

defineExpose({
  getTreeData,
  handleCreateType,
  handleDeleteType
})
</script>

<style scoped lang="scss">
.el-tree {
  margin-top: 16px;
  height: calc(100% - 100px);
  overflow-y: auto;
  :deep() {
    color: #515a6e;

    .is-current > .el-tree-node__content {
      color: #4a8ae9;
    }
  }
}
</style>
